<template>
  <ElCard shadow="never">
    <PlusPage
      ref="plusPageInstance"
      :is-card="false"
      :request="GroupServe.getList"
      :columns="columns"
      :params="state.query"
      :search="{ labelWidth: 'auto', colProps: { span: 8 } }"
      :table="{
        isSelection: true,
        actionBar: { buttons, width: 140 },
        onClickAction: handleTableOption,
        onSelectionChange: handleSelect
      }"
    >
      <template #table-title>
        <el-row class="button-row">
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            添加商品
          </el-button>
          <el-button :icon="Delete" type="danger" @click="handleBatchDelete">
            批量删除
          </el-button>
        </el-row>
      </template>
    </PlusPage>
    <!-- 弹窗编辑 -->
    <PlusDialogForm
      v-model:visible="visible"
      v-model="form"
      :form="{ columns, labelPosition: 'top', rules }"
      :dialog="{
        title: dialogTitle + '商品',
        width: '540px',
        top: '12vh',
        confirmLoading
      }"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    />

    <!-- 查看弹窗 -->
    <PlusDialog
      v-model="detailsVisible"
      width="600px"
      title="商品详情"
      top="26vh"
      :has-footer="false"
    >
      <PlusDescriptions :column="2" :columns="columns" :data="currentRow" />
    </PlusDialog>
  </ElCard>
</template>

<script lang="ts" setup>
import { computed, reactive, toRefs, ref, Ref, Fragment, h } from "vue";
import type { FormRules } from "element-plus";
import {
  ElButton,
  ElImage,
  ElMessage,
  ElMessageBox,
  ElUpload
} from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import type {
  ButtonsCallBackParams,
  PlusPageInstance,
  PlusColumn,
  OptionsRow
} from "plus-pro-components";
import goodApi from "@/api/good";

import { useTable } from "plus-pro-components";
import { useRouter } from "vue-router";
import { fileToDataURL } from "@plus-pro-components/utils";

import { useDictionary } from "@/utils/useDictionary";
const { GOOD, DICTIONARY } = useDictionary();
const router = useRouter();

interface TableRow {
  id: number;
}

interface State {
  /**
   * 检索数据
   */
  query?: any;
  /**
   * 当前选择的行数据
   */
  currentRow: Partial<TableRow>;
  /**
   * 表单弹窗是否可见
   */
  visible: boolean;
  /**
   * 详情弹窗是否可见
   */
  detailsVisible: boolean;
  /**
   * 当前选择多行的id集合
   */
  selectedIds: number[];
  /**
   *  提交loading
   */
  confirmLoading: boolean;
  /**
   * 是否是创建
   */
  isCreate: boolean;
  /**
   * 是否批量
   */
  isBatch: boolean;
  /**
   * 表单
   */
  form: {};
  /**
   * 校验
   */
  rules: FormRules;
}

/**
 * API
 */
const GroupServe = {
  async getList(query: Record<string, any>) {
    const { data } = await goodApi.goodPage(query);
    const { page = 1, pageSize = 10 } = query;
    const list = (data.list as TableRow[]).filter(
      (_, index) => index < pageSize * page && index >= pageSize * (page - 1)
    );
    return { data: list, total: data.total };
  },
  async create(data: Record<string, any>) {
    return data;
  },
  async update(data: Record<string, any>) {
    return data;
  },
  async delete(ids: number[]) {
    return await goodApi.goodDelete({ ids });
  },
  async getStatus() {
    return [];
  }
};

// options推荐写法
const upDownOptions: Ref<OptionsRow[]> = ref([]);
const specTypeOptions: Ref<OptionsRow[]> = ref([]);
const getOptions = async () => {
  const STATUS = await DICTIONARY(GOOD.GOOD_UPDOWN_STATUS);
  upDownOptions.value = STATUS.data;

  const SPEC = await DICTIONARY(GOOD.GOOD_SKU_TYPE);
  specTypeOptions.value = SPEC.data;
};
getOptions();

const plusPageInstance = ref<PlusPageInstance | null>(null);
const state = reactive<State>({
  query: {},
  currentRow: {},
  visible: false,
  detailsVisible: false,
  confirmLoading: false,
  isCreate: true,
  isBatch: false,
  selectedIds: [],
  form: {},
  rules: {}
});

const dialogTitle = computed(() => (state.isCreate ? "新增" : "编辑"));
const { buttons } = useTable();
const columns: PlusColumn[] = [
  {
    label: "id",
    width: 100,
    prop: "id"
  },
  {
    label: "商品名称",
    prop: "name"
  },
  {
    label: "商品图",
    prop: "img",
    valueType: "img",
    fieldProps: {
      style: {
        width: "100%"
      }
    },
    formatter: value => value.url
  },
  {
    label: "上架状态",
    prop: "status",
    valueType: "select",
    options: computed(() => upDownOptions.value)
  },
  {
    label: "规格类型",
    prop: "specType",
    valueType: "select",
    options: computed(() => specTypeOptions.value)
  },
  {
    label: "创建时间",
    prop: "createTime",
    valueType: "date-picker"
  },
  {
    label: "更新时间",
    prop: "updateTime",
    valueType: "date-picker",
    hideInSearch: true
  },
  {
    label: "商品简介",
    hideInSearch: true,
    valueType: "textarea",
    tableColumnProps: {
      showOverflowTooltip: true
    },
    prop: "description"
  }
];
// 按钮
buttons.value = [
  {
    text: "编辑",
    code: "update",
    props: { type: "success" }
  },
  {
    text: "删除",
    code: "delete",
    confirm: true,
    props: { type: "warning" }
  },
  {
    text: "查看",
    code: "view",
    props: { type: "info" }
  }
];

// 按钮操作
const handleTableOption = ({ row, buttonRow }: ButtonsCallBackParams): void => {
  state.currentRow = { ...row };
  switch (buttonRow.code) {
    case "update":
      router.push({
        name: "GoodAdd",
        query: {
          id: row.id
        }
      });
      break;
    case "delete":
      state.isBatch = false;
      handleDelete();
      break;
    case "view":
      state.detailsVisible = true;
      break;
  }
};

// 重新请求列表接口
const refresh = () => {
  plusPageInstance.value?.getList();
};

// 删除
const handleDelete = async (): Promise<void> => {
  try {
    const params = state.isBatch
      ? state.selectedIds
      : [state.currentRow.id as number];
    await GroupServe.delete(params);
    ElMessage.success("删除成功");
    refresh();
  } catch (error) {}
};

// 批量删除
const handleBatchDelete = async () => {
  if (!state.selectedIds.length) {
    ElMessage.warning("请选择数据！");
    return;
  }
  try {
    await ElMessageBox.confirm("确定删除所选数据", "提示");
    state.isBatch = true;
    handleDelete();
  } catch (error) {
    console.log(error);
  }
};

// 选择
const handleSelect = (data: any) => {
  state.selectedIds = [...data].map(item => item.id);
};

// 创建
const handleCreate = (): void => {
  router.push({
    name: "GoodAdd"
  });
};

// 取消
const handleCancel = () => {
  state.visible = false;
};

// 提交表单成功
const handleSubmit = async () => {
  try {
    state.confirmLoading = true;
    const params = { ...state.form };
    if (state.isCreate) {
      await GroupServe.create(params);
      ElMessage.success("创建成功");
    } else {
      await GroupServe.update(params);
      ElMessage.success("更新成功");
    }
    handleCancel();
    refresh();
  } catch (error) {}
  state.confirmLoading = false;
};

const { form, confirmLoading, rules, currentRow, visible, detailsVisible } =
  toRefs(state);
</script>
